package com.jiudao.service;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jiudao.dao.CustomerGADao;

/**
 * 
 * @author Administrator 客群分析 service
 */
@Service
public class CustomerGAService {

	@Autowired
	private CustomerGADao customerGADao;

	private final Gson gson = new Gson();
	private final Logger logger = Logger.getLogger(this.getClass());

	/**
	 * @param param
	 * @return String 客群分析数据查询
	 */
	@SuppressWarnings("serial")
	public String getData(final String param) {
		final JSONObject retObj = new JSONObject();
		try {
			final JsonObject jsonParam = gson.fromJson(param, JsonObject.class);
			final JsonObject arr = customerGADao.getData(jsonParam);

			final String[] type = { "ygqndata", "jycjdata", "xkzjdata", "jdyddata" };
			for (final String temp : type) {
				final JsonArray data = arr.get(temp).getAsJsonArray();
				final JSONArray rarr = new JSONArray();

				for (final JsonElement jsonElement : data) {
					final JsonObject obj = jsonElement.getAsJsonObject();
					final String name = obj.get("classname").getAsString();
					final long num = obj.get("num").getAsLong();
					final double tmount = obj.get("tmount").isJsonNull() ? 0 : obj.get("tmount").getAsDouble();
					rarr.add(new JSONObject() {
						{
							put("name", name);
							put("value", num);
							put("fee", tmount / num);
						}
					});
				}
				retObj.put(temp, rarr);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return retObj.toJSONString();
	}

}
